<?php

namespace Frieza\Modules\Tag\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\advertisement\MPositionBaseInfo;
use Doraemon\cache\PositionModule\Rules;
use Doraemon\model\AdmBigTag;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\BigTag\BigTag;
use Doraemon\service\BigTag\Schedule;
use Doraemon\service\position\AdmOperationModule;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class BigTagController extends Controller
{
    protected function initRequest(Request $request)
    {
        //初始化查询参数
        if (!$request->input('end_time')) {
            $request->merge([
                'end_time' => date('Y-m-d H:i:s'),
            ]);
        }
        return $request;
    }

    public function formatTimeRange(&$v, $nowDate = null)
    {
        if (is_null($nowDate)) $nowDate = time();


        if ($v['end_time'] > $nowDate || $v['time_type'] == 2) {
            if ($v['start_time'] < $nowDate) {
                $show_desc = '正在展示';
                $label = 'success';
            } else {
                $show_desc = '未上线';
                $label = 'warning';
            }
        } else {
            $show_desc = '已下架';
            $label = 'danger';
        }

        if ($v['time_type'] == 2) {
            $v['end_time'] = '永久生效';
        }

        $time_desc_template = "<span class=\"label label-{$label}\">%s</span>";
        $time_desc_item = [vsprintf($time_desc_template, [$show_desc])];
        array_push($time_desc_item, vsprintf($time_desc_template, [date("Y-m-d H:i:s", $v['start_time'])]));
        array_push($time_desc_item, vsprintf($time_desc_template, [is_numeric($v['end_time']) ? date("Y-m-d H:i:s", $v['end_time']) : $v['end_time']]));
        $v['label'] = $label;
        $v['show_desc'] = implode('<div class="p-1"></div>', $time_desc_item);
    }

    public function index(Request $request, Content $content)
    {
        $condition = [];
        $request = $this->initRequest($request);
        $all = $request->all();
        if (isset($all['end_time'])) $condition = ['OR' => [
            'end_time[>=]' => strtotime($all['end_time']),
            'time_type' => 2,
        ]];
        if (!empty($all['name'])) $condition['name'] = $all['name'];
        $list = AdmBigTag::getAll($condition);
        $nowDate = time();
        $link_ids = array_column($list, 'id');
        $rulesMap = \Doraemon\service\position\PositionApi::activeRules($link_ids, \Doraemon\model\Position\PositionRules::MODULE_TYPE_BIG_TAG);
        foreach ($list as &$v) {
            $this->formatTimeRange($v, $nowDate);
            $v['user_profile'] = $rulesMap[$v['id']] ?? [];
        }

        $gridModel = new pGridDataModel($list);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->paginate(20);
            $option = [1];
            $grid->filter(function (Grid\Filter $filter) use ($option) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('name', '大标签名称');
                });

                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    //时间筛选
                    $filter->equal('end_time', '截止日期')->datetime();
                });

                //条件展开
                if ($option) $filter->expand();
            });
            $grid->column('id')->sort();
            $grid->column('type', '标签类型')->using(AdmBigTag::BIG_TAG_TYPE_DESC);
            $grid->column('name', '大标签')->label();
            $grid->column('rela_tag', '关联标签');
            $grid->column('url', 'Url');
            $grid->column('tag_sort', '排序');
            $grid->column('show_desc', '展示状态')->display(function ($title, Grid\Column $column) {
                return $this->show_desc;
            });
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('aim', '投放目的')->using(MPositionBaseInfo::AIM_MAP);
            $grid->disablePagination();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if ($actions->row->type != AdmBigTag::BIG_TAG_TYPE_H5) {
                    $url = 'http://manage.haohaozhu.me/CarouselBanner/index/show_type/53?show_type=53&channel_tag=&start_date=' . date('Y-m-d') . '&end_date=' . date('Y-m-d') . '&topic_tag_id=' . $actions->row->id . '#';
                    $actions->append('<a target="_blank" href="' . $url . '">大标签Banner</a>');
                    $actions->append('&nbsp;&nbsp;<a target="_blank" href="http://manage.haohaozhu.me/Admin/ScrollCard/listing">走马灯配置</a>');
                }
            });
        });
        return $content
            ->header('大标签管理')
            ->breadcrumb(
                [
                    'text' => '大标签管理',
                    'url' => '/tag/bigTag/index'
                ]
            )
            ->body($listGrid->render());
    }

    public function sort(Request $request)
    {
        $sortInfo = $request->input('sort');
        foreach ($sortInfo as $id => $sort) {
            AdmBigTag::updateById($id, ['tag_sort' => $sort]);
        }
    }

    public function edit(Request $request, Content $content, $id = 0)
    {
        $info = [
            'time_type' => 1,
            'start_time' => date('Y-m-d 00:00:00', strtotime('1 day')),
            'end_time' => date('Y-m-d 23:59:59', strtotime('1 day'))
        ];
        $header = $id ? '编辑大标签' : '添加大标签';
        if ($id > 0) {
            $info = AdmBigTag::getById($id);
            $userProfile = AdmOperationModule::getPositionRulesById($id, PositionRules::MODULE_TYPE_BIG_TAG, true) ?: [];
            $info['user_profile'] = $userProfile;
            $info['start_time'] = date("Y-m-d H:i:s", $info['start_time']);
            $info['end_time'] = date("Y-m-d H:i:s", $info['end_time']);
            $tag_style = json_decode($info['tag_style'], true);
            if ($tag_style) {
                foreach ($tag_style as $key => $value) {
                    $info[$key] = $value;
                }
            }
        }

        $form = new Form($info);
        $form->radio('time_type', '展示时间')
            ->options([1 => '指定时间段', 2 => '永久生效'])
            ->when(1, function (Form $form) {
                $form->datetime('start_time', '开始显示时间');
                $form->datetime('end_time', '显示结束时间');
            })->when(2, function (Form $form) {
                $form->datetime('start_time', '开始显示时间');
            });

        $form->select('aim', '投放目的')->options(MPositionBaseInfo::AIM_MAP)->default(-1)->required()
            ->help("<a target='_blank' href='https://alidocs.dingtalk.com/i/nodes/ZgpG2NdyVXp0bY4OTxgXvLGgVMwvDqPk# 「投放目的操作手册与指南」'>投放目的操作手册与指南</a>");
        if ($id) {
            $form->select('type', '标签类型')->options(AdmBigTag::BIG_TAG_TYPE_DESC)->readOnly();
            if ($info['type'] == AdmBigTag::BIG_TAG_TYPE_H5) {
                $form->text('url', 'URL');
            }
            $form->text('id', '大标签ID')->readonly();
        } else {
            $form->fieldChange('type', '标签类型', $form)
                ->options(AdmBigTag::BIG_TAG_TYPE_DESC)
                ->default(0)
                ->callablePreCommon(function (Form $form) use ($info) {
                })->callableMap([
                    0 => function (Form $form) use ($info) {
                    },
                    1 => function (Form $form) {
                        $form->text('url', 'Url');
                    },
                    2 => function (Form $form) use ($info) {
                    },
                    3 => function (Form $form) use ($info) {
                    },
                ]);
        }

        $form->fieldChange('bg_color_type', ' ', $form)
            ->options([0 => '默认浅色', 1 => '深色'])
            ->bgColor('')
            ->default(0)
            ->callableMap([
                0 => function (Form $form) use ($info) {
                    $form->color('background_color', '背景色')->default('#FFFFFF')->help("小于4.9.0");
                    $form->color('background_color4', '背景色')->default('#F6F8F9')->help("大于等于4.9.0");
                    $form->color('tag_background_color', 'tag背景色')->default('#FFFFFF')->help("大于等于4.9.0");
                },
                1 => function (Form $form) {
                    $form->color('background_color', '背景色')->help("小于4.9.0");
                    $form->color('background_color4', '背景色')->default('#F6F8F9')->help("大于等于4.9.0");
                    $form->color('tag_background_color', 'tag背景色')->help("大于等于4.9.0");
                },
            ]);

        $form->divider('标签名称');
        $form->text('name', '标签名称')->required();
        $form->color('font_color_before', '字体颜色')->default('#333333');
        $form->number('font_color_before_opacity', '字体透明度')->default(100);
        $form->color('focus_color', '激活后字体颜色')->default('#000000');
        $form->number('focus_color_opacity', '激活后字体透明度')->default(100);
        $form->color('text_under_color', '激活后文字下划线颜色')->default('#000000')->help("小于4.9.0");
        $form->color('text_under_color4', '激活后文字下划线颜色')->default('#57E8D5')->help("大于等于4.9.0");

        $form->text('rela_tag', '关联标签');
        $form->textarea('top_ids', '指定位置插入指定内容:')->rows(10)->help('一行一个，obj_id|插入位置，例: 000nd0k00000orb0|5');

        $form->fieldChange('show_type', '展示方式', $form)
            ->options([0 => '使用文字', 1 => '使用图片'])
            ->default(0)
            ->callablePreCommon(function (Form $form) use ($info) {
            })->callableMap([
                0 => function (Form $form) use ($info) {
                },
                1 => function (Form $form) {
                    $form->text('tag_pic_url', '图片地址');
                    $form->text('tag_focus_pic_url', '激活后图片地址');
                },
            ]);

//        $form->divider('日历样式');
//        $form->radio('calendar_icon_type', '日历样式')->options([0 => '黑色', 1 => '白色']);
//        $form->number('calendar_icon_opacity', '日历icon透明度')->default(100);
//        $form->color('calendar_font_color', '日历中文字颜色')->default('#000000');
//        $form->number('calendar_font_opacity', '日历中文字透明度')->default(100);
//
//        $form->divider('搜索框样式');
//        $form->radio('search_icon_type', '搜索框样式')->options([0 => '黑色', 1 => '白色']);
//        $form->number('search_icon_opacity', '搜索框icon透明度')->default(100);
//        $form->color('search_background_color', '搜索框背景色')->default('#F5F5F5');
//        $form->number('search_background_opacity', '搜索框背景色透明度')->default(100);
//        $form->color('search_font_color', '搜索框中文字颜色')->default('#757575');
//        $form->number('search_font_opacity', '搜索框中文字透明度')->default(100);
//
//        $form->divider('消息图标样式');
//        $form->radio('message_icon_type', '消息图标样式')->options([0 => '黑色', 1 => '白色']);
//        $form->number('message_icon_opacity', '消息icon透明度')->default(100);
        $form->divider('用户分群');
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->action('/admin/tag/bigTag/save');

        return $content
            ->header($header)
            ->breadcrumb(
                [
                    'text' => '大标签管理',
                    'url' => '/tag/bigTag/index'
                ],
                ['text' => $header]
            )
            ->body($form->render());
    }

    public function save(Request $request)
    {
        $params = $request->all();
        try {
            $id = isset($params['id']) ? $params['id'] : 0;
            $userProfile = $request->input('user_profile', []);
            $url = '';
            if ($params['type'] == AdmBigTag::BIG_TAG_TYPE_H5 && isset($params['url'])) {
                $url = $params['url'];
            }
            $style = [
                'bg_color_type' => $params['bg_color_type'] ?? 0,
                'tag_background_color' => $params['tag_background_color'] ?? 0,
                'background_color' => (isset($params['background_color']) && strlen($params['background_color']) > 0) ? $params['background_color'] : '#ffffff',
                'background_color4' => (isset($params['background_color4']) && strlen($params['background_color4']) > 0) ? $params['background_color4'] : '#F6F8F9',
                'font_color_before' => (isset($params['font_color_before']) && strlen($params['font_color_before']) > 0) ? $params['font_color_before'] : '#333333',
                'font_color_before_opacity' => (isset($params['font_color_before_opacity']) && strlen($params['font_color_before_opacity']) > 0) ? $params['font_color_before_opacity'] : 100,
                'focus_color' => (isset($params['focus_color']) && strlen($params['focus_color']) > 0) ? $params['focus_color'] : '#000000',
                'focus_color_opacity' => (isset($params['focus_color_opacity']) && strlen($params['focus_color_opacity']) > 0) ? $params['focus_color_opacity'] : 100,
                'calendar_icon_type' => (isset($params['calendar_icon_type']) && strlen($params['calendar_icon_type']) > 0) ? $params['calendar_icon_type'] : 0,
                'calendar_icon_opacity' => (isset($params['calendar_icon_opacity']) && strlen($params['calendar_icon_opacity']) > 0) ? $params['calendar_icon_opacity'] : 100,
                'calendar_font_color' => (isset($params['calendar_font_color']) && strlen($params['calendar_font_color']) > 0) ? $params['calendar_font_color'] : '#000000',
                'calendar_font_opacity' => (isset($params['calendar_font_opacity']) && strlen($params['calendar_font_opacity']) > 0) ? $params['calendar_font_opacity'] : 100,
                'search_icon_type' => (isset($params['search_icon_type']) && strlen($params['search_icon_type']) > 0) ? $params['search_icon_type'] : 0,
                'search_background_color' => (isset($params['search_background_color']) && strlen($params['search_background_color']) > 0) ? $params['search_background_color'] : '#F5F5F5',
                'search_background_opacity' => (isset($params['search_background_opacity']) && strlen($params['search_background_opacity']) > 0) ? $params['search_background_opacity'] : 100,
                'search_icon_opacity' => (isset($params['search_icon_opacity']) && strlen($params['search_icon_opacity']) > 0) ? $params['search_icon_opacity'] : 100,
                'search_font_color' => (isset($params['search_font_color']) && strlen($params['search_font_color']) > 0) ? $params['search_font_color'] : '#757575',
                'search_font_opacity' => (isset($params['search_font_opacity']) && strlen($params['search_font_opacity']) > 0) ? $params['search_font_opacity'] : 100,
                'text_under_color' => (isset($params['text_under_color']) && strlen($params['text_under_color']) > 0) ? $params['text_under_color'] : '#000000',
                'text_under_color4' => (isset($params['text_under_color4']) && strlen($params['text_under_color4']) > 0) ? $params['text_under_color4'] : '#57E8D5',
                'message_icon_type' => (isset($params['message_icon_type']) && strlen($params['message_icon_type']) > 0) ? $params['message_icon_type'] : 0,
                'message_icon_opacity' => (isset($params['message_icon_opacity']) && strlen($params['message_icon_opacity']) > 0) ? $params['message_icon_opacity'] : 100,
            ];
            $data = [
                'name' => $params['name'],
                'aim' => $params['aim'],
                'type' => $params['type'],
                'time_type' => $params['time_type'] ?? '2',
                'start_time' => isset($params['start_time']) ? strtotime($params['start_time']) : 0,
                'end_time' => $params['end_time'] ? strtotime($params['end_time']) : 0,
                'url' => $url,
                'rela_tag' => $params['rela_tag'],
                'top_ids' => $params['top_ids'],
                'admin_id' => Admin::user()->id,
                'show_type' => $params['show_type'],
                'tag_style' => json_encode($style),
            ];

            if ($params['show_type'] == 1) {
                if (empty($params['tag_pic_url'])) {
                    throw  new \Exception('标签展示为图片时必填图片地址');
                }
                if (empty($params['tag_focus_pic_url'])) {
                    throw  new \Exception('标签展示为图片时必填激活时图片地址');
                }
                $data['tag_pic_url'] = $params['tag_pic_url'];
                $data['tag_focus_pic_url'] = $params['tag_focus_pic_url'];
            } else {
                $data['tag_pic_url'] = '';
                $data['tag_focus_pic_url'] = '';
            }
            if ($id) {
                $result = AdmBigTag::updateById($id, $data);
                if ($result) {
                    $big_tag_info = AdmBigTag::getById($id);
                    if ($big_tag_info['type'] == 0) {
                        // 购物大标签 单独处理
                        if ($params['name'] == BigTag::BIG_TAG_BUY_TEXT) {
                            Schedule::CreateBuyBigTag();
                        } else {
                            Schedule::BuildTagData($params['name']);
                            Schedule::BuildTagData3_17_5($params['name']);
                        }
                    } else if ($big_tag_info['type'] == AdmBigTag::BIG_TAG_TYPE_CITY) {
                        \Doraemon\service\SameCityTag\Schedule::BuildTagData($params['name']);
                    }
                } else {
                    throw  new \Exception("修改失败");
                }
            } else {
                if (AdmBigTag::count(['name' => $params['name']])) throw  new \Exception("标签名称已经存在", -1);
                $data['addtime'] = time();
                $id = AdmBigTag::addTag($data);
                if ($id) {
                    // type有0，1. 0是普通标签，1是h5网页
                    if ($params['type'] == AdmBigTag::BIG_TAG_TYPE_LIVING) {
                        // 购物大标签 单独处理
                        if ($params['name'] == BigTag::BIG_TAG_BUY_TEXT) {
                            Schedule::CreateBuyBigTag();
                        } else {
                            Schedule::BuildTagData($params['name']);
                            Schedule::BuildTagData3_17_5($params['name']);
                        }
                    } else if ($params['type'] == AdmBigTag::BIG_TAG_TYPE_CITY) {
                        \Doraemon\service\SameCityTag\Schedule::BuildTagData($params['name']);
                    }
                }
            }
            if ($id) {
                AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_BIG_TAG);

                Rules::delItem($id, Rules::getPrefixKey(PositionRules::MODULE_TYPE_BIG_TAG));
            } else {
                throw new \Exception('操作任务，数据库错误');
            }
            return back()->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } catch (\Exception $e) {
            if ($e->getCode() == -1) {
                return redirect('/admin/tag/bigTag/index?' . http_build_query(['name' => $params['name'], 'end_time' => "2000-01-01 00:00:00"]))->with('error', new MessageBag([
                    'title' => $e->getMessage()
                ]));
            }
            return back()->with('error', new MessageBag([
                'title' => $e->getMessage()
            ]));
        }
    }

    /**
     * 删除
     * @param $id
     * @return void
     */
    public function del(Request $request, $id)
    {
        $rs = AdmBigTag::deleteById($id);
        return response()->json([
            'status' => true,
            'message' => "操作成功",
        ]);
    }
}
